package com.qilin.hscs.aop;

import com.qilin.hscs.enums.ResultEnum;
import com.qilin.hscs.exception.SMException;
import com.qilin.hscs.util.TokenUtil;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by 10188 on 2018/5/4.
 */
@Aspect
@Component
@Order(1)
public class AuthenticationAspect {

    private static final Logger logger= LogManager.getLogger(AuthenticationAspect.class.getName());

    @Pointcut("execution(public * com.qilin.hscs.controller.*.*(..))")
    public void RoleController() {}


    @Before("RoleController()")
    public void doBefore(JoinPoint joinPoint) {
        logger.info("do Athentication");
        String name=joinPoint.getSignature().getName();
        switch (name) {
            case "login":
            case "register":
            case "handleError":
            case "getVerificationCode":
            case "resetPassword":
                break;
            default:
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = attributes.getRequest();
                String appointedToken = request.getHeader("authentication");
                if (appointedToken == null || !appointedToken.startsWith("qilin_")) {
                    throw new SMException(ResultEnum.INVALID_TOKEN);
                }
                String token = appointedToken.substring(6);
                logger.debug("token={}", token);
                try {
                    Claims claims = TokenUtil.parse(token);
                    String subject = claims.getSubject();
                    System.out.println(subject);
                } catch (Exception e) {
                    throw new SMException(ResultEnum.INVALID_TOKEN);
                }
        }
    }

}
